﻿namespace Web.Control.WWW.Session
{
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using Lx.Web.Common.ControlsUI;
    using System.Collections.Generic;
    using System.Collections;

    using System.Text;

    public class Session : BaseControl
    {
        protected string memberno = "";
        protected long sid = 0;
        /// <summary>
        /// 浏览者时区
        /// </summary>
        protected string Timezone = "0";        
        /// <summary>
        /// session信息
        /// </summary>
        protected Model.WWW_User.Teach.SessionsModel SM;
        /// <summary>
        /// 0学生学习工具 1老师教学工具
        /// </summary>
        protected List<string> IMAccountList;
        /// <summary>
        /// 当前用户类型1学生 2老师 0此session不是该用户的
        /// </summary>
        protected string UserType = "0";
        protected Repeater rptMsg;
        protected List<Model.WWW_User.Teach.History> HistoryList;

        protected string C0036 = "";
        
        protected System.Globalization.CultureInfo CurLan = new System.Globalization.CultureInfo(Lx.Web.Common.UI.Globals.Language);
        /// <summary>
        /// 当前用户时区跨度（用户时区－480）
        /// </summary>
        private double TZSpan;
        /// <summary>
        /// 支付连接
        /// </summary>
        string payUrl = "";

        protected override void OnLoad(EventArgs e)
        {           
            memberno = HttpContext.Current.User.Identity.Name;            
            if (string.IsNullOrEmpty(Request["sid"]))
            {
                Response.End();
                return;
            }
            if (memberno == "")
            {
                Page.Response.Redirect("/user/login.htm?ReturnUrl=" + Page.Request.Url.AbsoluteUri);
                return;
            }
            C0036 = GetText("C0036");
            payUrl = System.Configuration.ConfigurationManager.AppSettings["PayDetail"];
            long.TryParse(Request["sid"], out sid);

            ArrayList arrList = null;
            if (!string.IsNullOrEmpty(Request.Form["op"]))
            {
                string tToSDesc = string.IsNullOrEmpty(Request.Form["op"]) ? "" : Request.Form["tToSDesc"];
                arrList = BLF.WWW_User.Teach.Teach.GetASessionOp(memberno, sid, Request.Form["op"], tToSDesc);
            }
            else
            {
                arrList = BLF.WWW_User.Teach.Teach.GetASession(memberno, sid);
            }
            if (arrList != null)
            {
                UserType = (string)arrList[0];
                if (UserType == "0")
                {
                    Response.End();
                    return;
                }
                SM = arrList[1] as Model.WWW_User.Teach.SessionsModel;
                Timezone = (string)arrList[2];
                HistoryList = arrList[3] as List<Model.WWW_User.Teach.History>;
                IMAccountList = arrList[5] as List<string>;
                if (rptMsg != null)
                {
                    rptMsg.DataSource = arrList[4];
                    rptMsg.DataBind();
                }
                double.TryParse(Timezone, out TZSpan);
                TZSpan = TZSpan - 480;
            }
            else {
                Response.End();                
            }
            base.OnLoad(e);
        }
        protected string GetAgreedText()
        {
            string resourse1 = "<li>"+GetText("TP251")+"</li>";
            StringBuilder strAppend = new StringBuilder();
            string sAgr = "";
            string tAgr = "";
            int sflag = 0;
            int tflag = 0;
            foreach (Model.WWW_User.Teach.History his in HistoryList)
            {
                if (sflag == 0 && his.State == "0")
                {
                    sAgr = string.Format(resourse1, SM.SNickname, his.HappenDate.AddMinutes(TZSpan).ToString(TimeToString2, CurLan));
                    sflag++;
                }
                if (tflag == 0 && his.State == "5")
                {
                    tAgr = string.Format(resourse1, SM.TNickname, his.HappenDate.AddMinutes(TZSpan).ToString(TimeToString2, CurLan));
                    tflag++;
                }
            }
            strAppend.Append(sAgr);            
            strAppend.Append(tAgr);           
            return strAppend.ToString();
        }
        /// <summary>
        /// 获取历史操作记录文本
        /// </summary>
        /// <param name="state">操作状态</param>
        /// <param name="dtime">操作时间</param>
        /// <returns>历史操作记录文本</returns>
        protected string GetHistoryText(string state,DateTime dtime)
        {            
            string text = "";
            switch (state)
            {
                case "0":
                    if (IsHistoryState(state, "3"))//老师修改合同后，学生同意
                        text = GetText("TP930", new string[] { SM.SNO, SM.SNickname });
                    else//学生刚刚申请合同
                        text = GetText("TP931", new string[] { SM.SNO, SM.SNickname, SM.TNO, SM.TNickname });
                    break;
                case "1"://学生取消合同
                    text = GetText("TP932", new string[] { SM.SNO,"", SM.SNickname });
                    break;
                case "3"://老师修改合同
                    text = GetText("TP933", new string[] { SM.TNO, SM.TNickname });
                    break;
                case "4"://老师拒绝合同
                    text = GetText("TP932", new string[] { SM.TNO,"T", SM.TNickname });
                    break;
                case "5"://老师接受合同
                    text = GetText("TP934", new string[] { SM.TNO, SM.TNickname });
                    break;
                case "6"://学生已付款
                    text = GetText("TP935", new string[] { SM.SNO, SM.SNickname });
                    break;
                case "8"://老师申请取消
                    text = GetText("TP936", new string[] { SM.TNO, SM.TNickname });
                    break;
                case "9"://学生同意此课时无效
                    text = GetText("TP937", new string[] { SM.SNO, SM.SNickname });
                    break;
                case "A"://学生不同意此课时无效
                    text = GetText("TP938", new string[] { SM.SNO, SM.SNickname });
                    break;                
                case "B"://老师已确认上课
                    text = GetText("TP939", new string[] { SM.TNO,"T", SM.TNickname });
                    break;
                case "C"://学生投诉
                    text = GetText("TP940", new string[] { SM.SNO, SM.SNickname });
                    break;
                case "D"://学生投诉成功
                    text = GetText("TP941");
                    break;
                case "E"://学生投诉不成功
                    text = GetText("TP942");
                    break;
                case "F"://学生确认老师上课
                    text = GetText("TP939", new string[] { SM.SNO,"", SM.SNickname });
                    break;
                case "G"://老师已评价
                    text = GetText("TP943", new string[] { SM.TNO, SM.TNickname });
                    break;
                case "H"://老师提供了凭证
                    text = GetText("TP944", new string[] { SM.TNO, SM.TNickname });
                    break;
            }
            text = (text == "" ? "" : string.Format("<li>{0}{1}</li>", dtime.AddMinutes(TZSpan).ToString(TimeToString3, CurLan), text));
            return text;
        }

        /// <summary>
        /// 获取当前用户查看的session操作时间
        /// </summary>
        /// <param name="state">session状态</param>
        /// <param name="mtime">添加时间（分钟）</param>
        /// <returns>当前用户查看的session操作时间</returns>
        private DateTime GetHistoryTime(string state,double mtime)
        {            
            foreach (Model.WWW_User.Teach.History his in HistoryList)
            {
                if (his.State == state)
                {
                    return his.HappenDate.AddMinutes(mtime + TZSpan);//服务器时间转换用户时区时间                    
                }
            }
            return new DateTime();
        }
        /// <summary>
        /// 判断当前session state的上一个state是否为指定的状态
        /// </summary>
        /// <param name="state">session state</param>
        /// <returns>bool</returns>
        private bool IsHistoryState(string curState,string upState)
        {
            int flag = 1;
            foreach (Model.WWW_User.Teach.History his in HistoryList)
            {
                flag++;
                if (flag == 0 && his.State == upState)
                {
                    return true;
                }
                if (his.State == curState)
                {
                    flag = -1;
                }
            }
            return false;
        }
        protected string GetStateText()
        {
            string strText = "";
            switch (SM.State)
            {
                case "0"://开始申请(合同未确认) 7天确认
                    DateTime startTime = BLF.WWW_User.Teach.Teach.ConvertTime(SM.StartDate, SM.StartTime, Timezone);
                    DateTime dt = GetHistoryTime(SM.State, 7 * 24 * 60);
                    strText = GetText("TP901", new string[] { dt > startTime ? startTime.ToString(TimeToString1, CurLan) : dt.ToString(TimeToString1, CurLan) });
                    break;
                case "1"://学生取消了合同
                    strText = GetText("TP907");
                    break;
                case "2": //过时的课时
                    if (IsHistoryState("2", "3"))//学生未及时接受合同
                        strText = GetText("TP906");
                    else if (IsHistoryState("2", "5"))//学生未及时支付 24小时内
                        strText = GetText("TP909", new string[] { GetHistoryTime("5", 24 * 60).ToString(TimeToString1, CurLan) });
                    else//老师未及时接受合同
                        strText = GetText("TP923");
                    break;
                case "3"://老师修改了合同,合同未确认 (上课时间内确认)
                    strText = GetText("TP905", new string[] { BLF.WWW_User.Teach.Teach.ConvertTime(SM.StartDate, SM.StartTime, Timezone).ToString(TimeToString1, CurLan) });
                    break;
                case "4"://老师拒绝
                    strText = GetText("TP904");
                    break;
                case "5"://合同已确认
                    if (SM.Price > 0)//未支付的课时 (24小时内付款)
                    {
                        DateTime dt1 = BLF.WWW_User.Teach.Teach.ConvertTime(SM.StartDate, SM.StartTime, Timezone);
                        DateTime dt2 = GetHistoryTime(SM.State, 24 * 60);
                        strText = GetText("TP902", new string[] { dt1 > dt2 ? dt2.ToString(TimeToString1, CurLan) : dt1.ToString(TimeToString1, CurLan) });
                    }
                    else//  免费的课时
                        strText = GetText("TP903");
                    break;
                case "6"://已支付但课时未结束
                    if (BLF.WWW_User.Teach.Teach.ConvertTime(SM.StartDate, SM.StartTime, "480") > DateTime.Now)//课未开始
                        strText = GetText("TP908");
                    else//课在上
                        strText = GetText("TP910");
                    break;
                case "7"://课时已结束，老师还未确认 3天内确认
                    strText = GetText("TP911", new string[] { GetHistoryTime(SM.State, 3 * 24 * 60).ToString(TimeToString1, CurLan) });
                    break;
                case "8"://老师声明此课时无效 学生7天内同意
                    strText = GetText("TP913", new string[] { GetHistoryTime(SM.State, 7 * 24 * 60).ToString(TimeToString1, CurLan) });
                    break;
                case "9"://学生未采取任何行动、学生同意此课时无效
                    strText = GetText("TP915");
                    break;
                case "A":
                    if (IsHistoryState(SM.State, "8"))//学生不同意老师的声明
                        strText = GetText("TP916");
                    else//老师未及时确认课时
                        strText = GetText("TP914");
                    break;
                case "B"://学生还未确认课时,老师已确认上完课  学生7天内确认
                    strText = GetText("TP912", new string[] { GetHistoryTime(SM.State, 7 * 24 * 60).ToString(TimeToString1, CurLan) });
                    break;
                case "C"://学生申请退款 老师14天内解释
                    strText = GetText("TP918"
                       , new string[] { GetHistoryTime(SM.State, 14 * 24 * 60).ToString(TimeToString1, CurLan) });
                    break;
                case "D"://退款到学生：老师未提供凭证、凭证无效
                    strText = GetText("TP921");
                    break;
                case "E":
                    strText = GetText("TP922", new string[] { GetHistoryTime(SM.State, 7 * 24 * 60).ToString(TimeToString1, CurLan) });
                    break;
                case "G":
                case "F"://成功交易
                    if ((DateTime.Now.Subtract(GetHistoryTime("B", -TZSpan)).TotalDays) > 7)//老师已确认但学生未确认
                        strText = GetText("TP919"
                            , new string[] { GetHistoryTime(SM.State, 7 * 24 * 60).ToString(TimeToString1, CurLan) });
                    else //双方已确认上课
                        strText = GetText("TP917", new string[] { GetHistoryTime(SM.State, 7 * 24 * 60).ToString(TimeToString1, CurLan) });
                    break;
                case "H"://退款申请待决,italki审核中
                    strText = GetText("TP920");
                    break;
            }
            if (UserType == "1")//学生操作
            {
                switch (SM.State)
                {//"1":学生取消申请、"4":老师拒绝、"G":老师feedback
                    case "0":
                        //strText += string.Format("<div><a href='/session/sessionstate0.htm?sid={0}'>{1}</a>&nbsp;&nbsp;<a href='#' onclick='OP(\"1\")'>{2}</a></div>", sid, GetText("TP107"), GetText("TP140"));
                        strText += string.Format("<div><a href='#' onclick='OP(\"1\")'>{0}</a></div>", GetText("TP140"));
                        break;
                    case "3":
                        //strText += string.Format("<div><a href='/session/sessionstate0.htm?sid={0}'>{1}</a>&nbsp;&nbsp;<a href='#' onclick='OP(\"1\")'>{2}</a></div>", sid, GetText("TP139"), GetText("TP140"));
                        strText += string.Format("<div><a href='{0}'>{1}</a>&nbsp;&nbsp;<a href='#' onclick='OP(\"1\")'>{2}</a></div>", string.Format(payUrl, sid), GetText("TP141"), GetText("TP140"));
                        break;
                    case "5":
                        if (SM.Price > 0)
                            strText += string.Format("<div><a href='{1}'>{0}</a></div>", GetText("TP141"), string.Format(payUrl, sid));
                        break;
                    case "8":
                        strText += string.Format("<div><a href='/session/sessionstate9a.htm?sid={0}'>{1}</a>&nbsp;&nbsp;<a href='/session/sessionstate9a.htm?sid={0}'>{2}</a></div>", sid, GetText("TP112"), GetText("TP113"));
                        break;
                    case "B":
                        strText += string.Format("<div><a href='/session/sessionstatef.htm?sid={0}'>{1}</a>&nbsp;&nbsp;<a href='/session/sessionstatec.htm?sid={0}'>{2}</a></div>", sid, GetText("TP142"), GetText("TP144"));
                        break;
                }
            }
            else if (UserType == "2")//教师操作
            {
                switch (SM.State)
                {
                    case "0":
                        strText += string.Format("<div><a href='#' onclick='OP(\"5\")'>{3}</a>&nbsp;&nbsp;<a href='/session/sessionstate3.htm?sid={0}'>{1}</a>&nbsp;&nbsp;<a href='#' onclick='OP(\"4\")'>{2}</a></div>", sid, GetText("修改"), GetText("TP138"), GetText("同意"));
                        break;
                    case "3":
                        strText += string.Format("<div><a href='/session/sessionstate3.htm?sid={0}'>{1}</a>&nbsp;&nbsp;<a href='#' onclick='OP(\"4\")'>{2}</a></div>", sid, GetText("TP137"), GetText("TP138"));
                        break;
                    case "7":
                        strText += string.Format("<div><a href='/session/sessionstateb.htm?sid={0}'>{1}</a>&nbsp;&nbsp;<a href='/session/sessionstate8.htm?sid={0}'>{2}</a></div>", sid, GetText("TP142"), GetText("TP143"));
                        break;
                    case "C":
                        strText += string.Format("<div><a href='/session/sessionstateh.htm?sid={0}'>{1}</a></div>", sid, GetText("TP145"));
                        break;
                    case "E":
                    case "F":
                        if ((DateTime.Now.Subtract(GetHistoryTime(SM.State, -TZSpan)).TotalDays) > 7)
                            strText += string.Format("<div><a href='Feedback({0})'>{1}</a></div>", sid, GetText("TP146"));
                        break;
                }
            }
            return strText;
        }
    }
}